﻿using JoceLinItemDemo.Application.UserInfoMessage.Dto;
using JoceLinItemDemo.Domain.UserInfoMessage;
using JoceLinItemDemo.Service;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace JoceLinItemDemo.Application.UserInfoMessage
{
    public class UserInfoMessageAppService : ApplicationService , IUserInfoMessageAppService
    {
        //注入服务
        private readonly IRepository<UserInfoMe> _userinfome;
        public UserInfoMessageAppService(IRepository<UserInfoMe> userinfome)
        {
            _userinfome = userinfome; 
        }

        //实例化全局对象
        ConfigSet config = new ConfigSet();

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="userInfoMessageDto"></param>
        /// <returns></returns>
        public async Task<UserInfoMe> InsertUserInfoManager(UserInfoMessageDto userInfoMessageDto)
        {
            UserInfoMe userInfoMe=ObjectMapper.Map<UserInfoMessageDto,UserInfoMe>(userInfoMessageDto);
            return await _userinfome.InsertAsync(userInfoMe);
        }
        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task DeleteUserInfoManager(string Id) 
        {
            var userlist = _userinfome.Where(s => s.Id == Id).FirstOrDefault();
            await _userinfome.DeleteAsync(userlist);
        }
        /// <summary>
        /// 批量删除用户信息
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public async Task DeleteUserInfoManagerByAny(string Ids)  
        {
            string[] obj = Ids.Split(',');

            foreach (string item in obj)
            {
                var list = _userinfome.Where(s => s.Id == item).FirstOrDefault();

                await _userinfome.DeleteAsync(list);
            }
        }
        /// <summary>
        /// 查看用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public dynamic FindUserInfoManager(string Id)
        {
            var list = _userinfome.Where(s => s.Id == Id).FirstOrDefault();
            return list;
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> UpdateUserInfoManager(UserInfoMessageDto userInfoMessageDto)
        {
            UserInfoMe userInfoMe = ObjectMapper.Map<UserInfoMessageDto, UserInfoMe>(userInfoMessageDto);

            var list = _userinfome.GetDbSet<UserInfoMe>();

            list.Update(userInfoMe);

            return true;
        }
        /// <summary>
        /// 分页显示用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public dynamic GetUserInfoManagerByPage(int pageIndex, int pageSize)
        {
            var query = _userinfome.AsQueryable();

            var userlist = from user in query 
                        select new 
                        {
                            Id = user.Id,
                            UserName = user.UserName,
                            UserAge=user.UserAge,
                            UserSex=user.UserSex,
                            UserMobile=user.UserMobile,
                            UserAddress=user.UserAddress,
                            CreateDate = user.CreateDate.Year + "/" + user.CreateDate.Month + "/" + user.CreateDate.Day,
                            CreateUser=user.CreateUser,
                            UpdateDate= user.UpdateDate.Year + "/" + user.UpdateDate.Month + "/" + user.UpdateDate.Day,
                            UpdateUser= user.UpdateUser
                        };

            var slist = userlist.ToList();

            //把slist分成config.DataNum份数
            var result = SplitList(slist, config.DataNum);

            //线程工厂，实例化线程集合
            TaskFactory taskFactory = new TaskFactory();
            List<Task> taskList = new List<Task>();
            List<UserInfoMe> AllList = new List<UserInfoMe>();
            ArrayList array = new ArrayList();

            for (int i = 0; i < result.Count; i++)
            {
                string index = Convert.ToString(i);
                taskList.Add(Task.Run(() =>
                {
                    var klist = result[Convert.ToInt32(index)];
                    for (int k = 0; k < klist.Count; k++)
                    {
                        //处理业务
                    }
                }));
            }
            taskFactory.ContinueWhenAll(taskList.ToArray(), tList =>
            {
                Console.WriteLine("所有线程已经执行完毕！");
            });

            //var pagelist = new
            //{
            //    totalCount = array.Count,
            //    data = array.ToArray().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(),
            //};
            //return pagelist;

            var pagelist = new
            {
                totalCount = query.Count(),
                data = userlist.OrderBy(s => s.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(),
            };
            return pagelist;
        }

        /// <summary>
        /// 通过指定数量进行均分
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Lists"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        public static List<List<T>> SplitList<T>(List<T> Lists, int num)
        {
            List<List<T>> result = new List<List<T>>();

            if (Lists.Count >= num)
            {
                // 每组的数量
                int avg = Lists.Count / num;
                // 余数
                int vag = Lists.Count % num;

                for (int i = 0; i < num; i++)
                {
                    List<T> cList = new List<T>();
                    if (i + 1 == num)
                    {
                        cList = Lists.Skip(avg * i).ToList();
                    }
                    else
                    {
                        cList = Lists.Skip(avg * i).Take(avg).ToList<T>();
                    }
                    result.Add(cList);
                }
            }
            else
            {
                // 最后一组
                result.Add(Lists);
            }
            return result;
        }
    }
}
